package demo2;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 28779
 * Date: 2023-04-02
 * Time: 11:07
 */
public class SeqList {
    private int[] elem;
    private int usedSize;//记录当前顺序表当中 有多少个有效的数据
    private static final int DEFAULT_CAPACITY = 10;

    public SeqList() {
        this.elem = new int[DEFAULT_CAPACITY];
    }

    // 打印顺序表，注意：该方法并不是顺序表中的方法，为了方便看测试结果给出的
    public void display() {
        for (int i = 0; i < this.usedSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
        System.out.println();
    }

    public void add(int data){
        //首先要判断
        if(ifFull()){    //利用函数，判断满了需要扩容
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        this.elem[usedSize] = data;
        usedSize++;
    }

    public boolean ifFull(){
        return usedSize == elem.length;
    }
    
    // 判定是否包含某个元素
    public boolean contains(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if(elem[i] == toFind){
                return true;
            }
        }
        return false;
    }
    // 查找某个元素对应的位置
    public int indexOf(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if (elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }
    // 获取 pos 位置的元素
    public int get(int pos) {
        for (int i = 0; i < this.usedSize; i++) {
            if(i == pos){
                return elem[i];
            }
        }
        return -1;
    }

    //删除第一次出现的关键字key
    public void remove(int toRemove) {
        int ret = -1;
        for (int i = 0; i < this.usedSize; i++) {
            if(elem[i] == toRemove){
                ret = i;
                break;
            }
        }
        for (int i = ret; i < this.usedSize - 1; i++) {
            this.elem[i] = this.elem[i+1];
        }
        this.usedSize--;
    }
}
